package com.common.manager;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PreDestroy;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class TimeCostBeanPostProcessor implements BeanPostProcessor {
	
	private Map<String, Long> costMap = new ConcurrentHashMap<>();

	@Value("${system.beanCostTime:500}")
	private Integer costTime;
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		costMap.put(beanName, System.currentTimeMillis());
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (costMap.containsKey(beanName)) {
			Long start = costMap.get(beanName);
			long cost = System.currentTimeMillis() - start;
			if (cost > costTime) {
				log.warn("bean: " + beanName + " cost time: " + cost+" 毫秒");
			}
		}
		return bean;
	}
	
	@PreDestroy
	public void destroy() {
		costMap.clear();
		costMap=null;
	}
}
